package com.qf.netty.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.netty.entity.Message;
import com.qf.netty.entity.Rooms;
import com.qf.netty.handler.base.BaseMsgChannelHandler;
import com.qf.netty.utils.RoomUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.kurento.client.EventListener;
import org.kurento.client.IceCandidateFoundEvent;
import org.kurento.client.WebRtcEndpoint;
import org.springframework.stereotype.Component;

/**
 * 主播的提案信息的处理
 * author Ken
 * create_time 2023/1/5
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class MasterOfferMsgChannelHandler extends BaseMsgChannelHandler {


    @Override
    protected int action() {
        return 3;
    }

    @Override
    protected void handler(ChannelHandlerContext ctx, Message msg) {
        //获取到提案的相关信息 - json
        //进一步解析其中的数据
        JSONObject jsonObject = (JSONObject) msg.getMsg();
        //获取房间号
        Integer roomId = Integer.parseInt(jsonObject.getString("roomId"));
        //获取提案的SDP
        String sdp = jsonObject.getString("offer");

        //获取当前主播的房间
        Rooms rooms = RoomUtils.getRooms(roomId);

        //获取主播方的端点对象
        WebRtcEndpoint webRtcEndpoint = rooms.getMaster().getWebRtcEndpoint();

        //设置端点的ICE候选者的监听回调 - KMS的ICE候选者
        webRtcEndpoint.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {
            @Override
            public void onEvent(IceCandidateFoundEvent event) {
                 log.info("[KMS Ice] KMS服务器的ICE候选者监听回调 - {}", event.getCandidate().getCandidate());
                 //将KMS候选者地址 发给直播方
                 Message message = new Message()
                         .setAction(5)
                         .setMsg(JSON.toJSONString(event.getCandidate()));
                ctx.writeAndFlush(message);
            }
        });

        //将直播方的提案的Sdp传递给KMS,KMS会返回一个应答的SDP
        String answerSdp = webRtcEndpoint.processOffer(sdp);

        //将应答的SDP返回给直播方
        Message message = new Message()
                .setAction(4)
                .setMsg(answerSdp);
        //将当前消息传回给主播方
        ctx.writeAndFlush(message);

        //开启KMS的ICE候选者监听
        webRtcEndpoint.gatherCandidates();
    }
}
